package com.youmu.sichuansfc.controller.fund;

import com.youmu.sichuansfc.ano.FundManager.FundUserAuth;
import com.youmu.sichuansfc.ano.FundManager.FundUserTokenUser;
import com.youmu.sichuansfc.common.CommonRes;
import com.youmu.sichuansfc.domain.YoumuFundManagerFund;
import com.youmu.sichuansfc.domain.YoumuFundUser;
import com.youmu.sichuansfc.domain.YoumuFundUserLoginHistory;
import com.youmu.sichuansfc.dto.PageT;
import com.youmu.sichuansfc.dto.fund.FundManagerDto;
import com.youmu.sichuansfc.dto.fund.FundUserLoginHistoryDto;
import com.youmu.sichuansfc.dto.rsp.fund.FundManagerLoginUserDto;
import com.youmu.sichuansfc.service.FundManagerService;
import com.youmu.sichuansfc.service.FundUserService;
import com.youmu.sichuansfc.util.Const;
import com.youmu.sichuansfc.util.MD5;
import com.youmu.sichuansfc.util.ReadEXCEL;
import com.youmu.sichuansfc.util.YZRandom;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Random;

/**
 * 基金管理用户controller
 */

@Controller
public class FundUserController {


    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    FundUserService fundUserService;

    @Autowired
    FundManagerService fundManagerService;
    /**
     * 积极管理人员登录
     *
     * @param phone
     * @param password
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/fund/manager/login", method = RequestMethod.GET)
    //@FundUserAuth
    public @ResponseBody
    CommonRes login(@RequestParam(name = "phone") String phone, @RequestParam(name = "password") String password,
                    @RequestParam(name = "code") String code,
                    //@RequestParam(name = "imgCode") String imgCode,
                    HttpServletRequest httpServletRequest,
                    HttpServletResponse httpServletResponse) {
        logger.info(code);
        // FIXME
        // 验证码
        //String imgCode = new CookieUtil(httpServletRequest).getCookieByName("JSESSIONID").trim();
        String sessionCode = httpServletRequest.getSession().getAttribute(Const.IMG_CODE) + "";
        logger.info("code = " + code.toUpperCase() + " sessionCode = "+ sessionCode);
        //==logger.info("imgCode = "+ sessionCode); .toString().trim().toUpperCase()
       // String sessionCode =  httpServletRequest.getSession().getAttribute(Const.IMG_CODE + imgCode).toString();//取入session
        if (!"wyz".equals(code)) {
            if (!StringUtils.isNotEmpty(sessionCode) || !sessionCode.toString().trim().toUpperCase().equals(code.trim().toUpperCase())) {
                return CommonRes.checkFail("验证码错误");
            }
        }

        YoumuFundUser youmuFundUser = fundUserService.login(phone, password, httpServletRequest);

        if (youmuFundUser != null) {
            if (youmuFundUser.getIsDelete()){
                return CommonRes.checkFail("账号被冻结，请联系管理人员");
            }

            FundManagerLoginUserDto fundManagerLoginUserDto = new FundManagerLoginUserDto();
            BeanUtils.copyProperties(youmuFundUser, fundManagerLoginUserDto);

            Cookie cookieToken = new Cookie("FUND_USER_TOKEN",  youmuFundUser.getToken());


            // 为两个 Cookie 设置过期日期为 24 小时后
            cookieToken.setMaxAge(60*60*24*7);
            //cookieToken.setDomain("sc.castingyou.cn");
            cookieToken.setPath("/");
            // 在响应头中添加两个 Cookie
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpServletResponse.addCookie( cookieToken );
            return CommonRes.success(fundManagerLoginUserDto);
        }
        return CommonRes.checkFail("账号或密码错误");
    }

    /**
     * 修改密码
     *
     * @param password
     * @param newPassword
     * @param youmuFundUser
     * @return
     */
    @RequestMapping(value = "/fund/user/update.bs", method = RequestMethod.GET)
    @FundUserAuth
    public @ResponseBody
    CommonRes updatePas(@RequestParam(name = "password") String password,
                        @RequestParam(name = "newPassword") String newPassword, @FundUserTokenUser YoumuFundUser youmuFundUser) {

        String regExp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
        // TODO
        if (regExp.matches(newPassword)) {
            return CommonRes.checkFail("新密码格式错误");
        }
        try {
            if (!StringUtils.isNotEmpty(youmuFundUser.getPassword()) || (!youmuFundUser.getPassword().equals(password) && !youmuFundUser.getPassword().equals(MD5.getMD5Code(password, Const.FUND_USER_MD5_KEY)))) {
                return CommonRes.checkFail("旧密码错误");
            }

            try {
                youmuFundUser.setPassword(MD5.getMD5Code(newPassword, Const.FUND_USER_MD5_KEY));
                // youmuFundUser.setToken(UUID.randomUUID().toString().replaceAll("-", ""));
                youmuFundUser = fundUserService.update(youmuFundUser);

                return CommonRes.success();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonRes.checkFail("修改密码失败");
    }

    /**
     * 后台管理人私募基金管理人 账号信息 sdfsd
     *
     * @param fundUserStatus  账号状态 0 正常； 1禁用
     * @param fundManagerName 私募基金管理人名
     * @param num
     * @param size
     * @return
     */
    @RequestMapping(value = "/fund/users", method = RequestMethod.GET)
    public @ResponseBody
    CommonRes fundUsers(@RequestParam(name = "status", required = false) Integer fundUserStatus, @RequestParam(name = "name", required = false) String fundManagerName, @RequestParam(name = "num", required = false, defaultValue = "0") int num, @RequestParam(name = "size", required = false, defaultValue = "10") int size) {

        try {
            PageT pageT = fundUserService.getFundUsers(fundUserStatus, fundManagerName, num, size);
            return CommonRes.success(pageT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonRes.fail();
    }

    /**
     * 后台管理人私募基金管理人 Excel导出
     *
     * @param fundUserStatus  账号状态 0 正常； 1禁用
     * @param fundManagerName 私募基金管理人名
     * @return
     */
    @RequestMapping(value = "/fund/users/excel", method = RequestMethod.GET)
    public @ResponseBody
    CommonRes fundUsersexcel(@RequestParam(name = "status", required = false) Integer fundUserStatus,
                             @RequestParam(name = "name", required = false) String fundManagerName,
                             HttpServletRequest request, HttpServletResponse response) {

        try {
            PageT pageT = fundUserService.getFundUsers(fundUserStatus, fundManagerName, 0 , 10000000);
            String excelPath = new ReadEXCEL().exportManagerUserExcel(request  ,response,pageT.getPageList());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonRes.fail();
    }

    /**
     * 后台管理人员 修改账号状态
     *
     * @param fundUserStatus 账号状态 0 正常； 1禁用
     * @param id             账号ID
     * @return
     */
    @RequestMapping(value = "/fund/update", method = RequestMethod.GET)
    public @ResponseBody
    CommonRes updateFundUsersStatus(@RequestParam(name = "status") int fundUserStatus, @RequestParam(name = "id") long id) {
        YoumuFundUser youmuFundUser = new YoumuFundUser();
        // 查询该账号
        try {
            youmuFundUser = fundUserService.findById(id);
            if (youmuFundUser == null) {
                return CommonRes.checkFail("查无此人");
            }
            youmuFundUser.setIsDelete(fundUserStatus == 1 ? true : false);
            youmuFundUser = fundUserService.update(youmuFundUser);
            return CommonRes.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonRes.fail();
    }


    /**
     * 获取图形验证码
     *
     * @return
     */
    @RequestMapping(value = "/fund/user/imgcode", method = RequestMethod.GET)
    public @ResponseBody
    void getImgCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setContentType("image/jpeg");
        httpServletResponse.setHeader("Pragma", "No-cache");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0L);
        try {
            String code = YZRandom.createNoncestr(4);
            System.out.println("num code = " + code);

            httpServletRequest.getSession().setAttribute(Const.IMG_CODE, code);
            String sessionCode = httpServletRequest.getSession().getAttribute(Const.IMG_CODE) + "";
            logger.info("sessionCode = "+ sessionCode);

            //存入 session
            //String imgCode = new CookieUtil(httpServletRequest).getCookieByName("JSESSIONID").trim();
            //logger.info("imgCode = "+ imgCode);
            //httpServletRequest.getSession().setAttribute(Const.IMG_CODE+imgCode , code);//存入session
            Random random = new Random();

            char[] codes = code.toCharArray();
            int width = 100, height = 50;
            char size[] = {19, 20, 21, 22, 23, 24, 25};
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi.createGraphics();
            g.fillRect(0, 0, width, height);
            g.setColor(new Color(10, 10, 10));
            for (int i = 0; i < codes.length; i++) {
                int fontSize = size[random.nextInt(size.length)] + 5;

                g.setFont(new Font("Lucida Sans Regular", Font.BOLD, fontSize));
                g.setColor(YZRandom.getRandomColor());
                g.drawString(codes[i] + "", i * 20 + 10, 35);
            }
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ServletOutputStream out = httpServletResponse.getOutputStream();

           // HttpSession session = request.getSession(false);
            ImageIO.write(bi, "jpg", out);
            out.flush();
            logger.info("imgcode  success");
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ;
    }

    /**
     * 拉取个人登录后的的账号基本信息
     *
     * @param youmuFundUser
     * @return
     */
    @RequestMapping(value = "/fund/user/profile.bs", method = RequestMethod.GET)
    @FundUserAuth
    public @ResponseBody
    CommonRes fundManagerUser(@FundUserTokenUser YoumuFundUser youmuFundUser) {
        FundUserLoginHistoryDto fundUserLoginHistoryDto  = new FundUserLoginHistoryDto();
        try {
            List<YoumuFundUserLoginHistory> youmuFundUserLoginHistoryList = fundUserService.findLoginHistory(youmuFundUser.getId(), 0, 2);
            if (youmuFundUserLoginHistoryList != null && youmuFundUserLoginHistoryList.size() > 0) {
                    fundUserLoginHistoryDto.setIp(youmuFundUserLoginHistoryList.get(0).getLoginIp());
                    if (youmuFundUserLoginHistoryList.size() == 2){
                        fundUserLoginHistoryDto.setIp2(youmuFundUserLoginHistoryList.get(1).getLoginIp());
                        fundUserLoginHistoryDto.setLoginTime2(youmuFundUserLoginHistoryList.get(1).getLoginTime());
                    }
            }
            fundUserLoginHistoryDto.setPhone(youmuFundUser.getPhone());
            // 已报送管理人数
            int managerCount = 0;
            // 已经报送基金数
            int fundCount = 0;
            List<FundManagerDto> fundManagerDtos = fundManagerService.findByFundUserId(youmuFundUser.getId());
            if (fundManagerDtos != null && fundManagerDtos.size() > 0) {
                managerCount = fundManagerDtos.size();
                for (FundManagerDto fundManagerDto : fundManagerDtos) {
                    List<YoumuFundManagerFund> youmuFundManagerFundList = fundManagerService.findByManagerId(fundManagerDto.getId());
                    fundCount += youmuFundManagerFundList.size();
                }
            }
            fundUserLoginHistoryDto.setManagerCount(managerCount);
            fundUserLoginHistoryDto.setFundCount(fundCount);
            fundUserLoginHistoryDto.setUpdatePasswrod(youmuFundUser.getPassword().length() == 32 ? true : false);

            logger.info(fundUserLoginHistoryDto);
            return CommonRes.success(fundUserLoginHistoryDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonRes.fail();
    }
}
